import Vue from 'vue'
import Router from 'vue-router'
import store from '../store'
// 计划管理
import planningManage from './planningManage'
// 生产准备
import productionPrepare from './productionPrepare'
// 生产管理
import productionManage from './productionManage'
// 质量管理
import qualityManage from './qualityManage'
// 数据采集
import dataAcquisition from './dataAcquisition'
// 追踪与追溯
import tracing from './tracing'
// 资源管理
import resourceManage from './resourceManage'
// 文档管理
import documentManage from './documentManage'
// 报表管理
import reportManage from './reportManage'
// 车间看板
import workshopView from './workshopView'
// 基础数据
import sysMan from './sysMan'
import demo from './demo'
import backToList from '../utils/backToList'

Vue.use(Router)

const router = new Router({
  routes: [
    /* 首页 */
    {
      path: '/',
      component(resolve) {
        require(['../view/layout/Layout'], resolve)
      },
      children: [
        ...demo,
        ...planningManage,
        ...productionPrepare,
        ...productionManage,
        ...resourceManage,
        ...dataAcquisition,
        ...reportManage,
        ...qualityManage,
        ...tracing,
        ...workshopView,
        ...documentManage,
        ...sysMan,
        {
          path: '/',
          name: 'welcome',
          component(resolve) {
            require(['../view/layout/components/WelcomePage'], resolve)
          },
          meta: {
            title: '欢迎页'
          }
        },
      ]
    }
  ]
})

router.beforeEach((to, from, next) => {
  let arr = store.state.userTree || []
  let rootDir = arr.find(item => item.href === to.meta.rootDir) || {children: []}
  let subMenu = rootDir.children.find(item => item.href === to.meta.subMenu) || {children: []}
  let menuItem = subMenu.children.find(item => item.href === to.meta.menuItem)
  if (!store.state.userTree) {
    next()
  } else if (!menuItem && to.meta.menuItem) {
    next(false)
  } else {
    backToList(to, from).finally(() => {
      next()
    })
  }
})

export default router
